package com.thor.palmmall.util.http;

  import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Encoder;

import net.sf.json.JSONObject;  
/**
 * Http请求工具类,发送json返回json
 * 
 * 除了要导入json-lib-2.1.jar之外，还必须有其它几个依赖包： commons-beanutils.jar
 * commons-httpclient.jar commons-lang.jar ezmorph.jar morph-1.0.1.jar
 * 另外，commons-collections.jar也需要导入
 */
public class HttpRequestUtil {

  private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
  
  public static JSONObject httpPostApi(String url, JSONObject jsonParam, boolean noNeedResponse) {

    // post请求返回结果
    DefaultHttpClient httpClient = new DefaultHttpClient();
    JSONObject jsonResult = null;
    HttpPost method = new HttpPost(url);
    try {
      if (null != jsonParam) {
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        method.addHeader("Accept", "application/json; charset=utf-8");
        method.addHeader("Content-Signature", "HMAC-SHA1 " + new String(new BASE64Encoder().encode("638db0abfb6877bf3d130399c792155e".getBytes())));
        method.setEntity(entity);
      }
      HttpResponse result = httpClient.execute(method);
      url = URLDecoder.decode(url, "UTF-8");
      /** 请求发送成功，并得到响应 **/
      if (result.getStatusLine().getStatusCode() == 200) {
        String str = "";
        try {
          /** 读取服务器返回过来的json字符串数据 **/
          str = EntityUtils.toString(result.getEntity());
          if (noNeedResponse) {
            return null;
          }
          /** 把json字符串转换成json对象 **/
          jsonResult = JSONObject.fromObject(str);
        } catch (Exception e) {
          logger.error("post请求提交失败:" + url, e);
        }
      }
    } catch (IOException e) {
      logger.error("post请求提交失败:" + url, e);
    }
    return jsonResult;
  }
  
  /**
   * 发送get请求
   * 
   * @param url
   *          路径
   * @return
   */
  public static JSONObject httpGet(String url) {

    // get请求返回结果
    JSONObject jsonResult = null;
    try {
      DefaultHttpClient client = new DefaultHttpClient();
      // 发送get请求
      HttpGet request = new HttpGet(url);
      HttpResponse response = client.execute(request);

      /** 请求发送成功，并得到响应 **/
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        /** 读取服务器返回过来的json字符串数据 **/
        String strResult = EntityUtils.toString(response.getEntity());
        /** 把json字符串转换成json对象 **/
        jsonResult = JSONObject.fromObject(strResult);
        url = URLDecoder.decode(url, "UTF-8");
      } else {
        logger.error("get请求提交失败:" + url);
      }
    } catch (IOException e) {
      logger.error("get请求提交失败:" + url, e);
    }
    return jsonResult;
  }

  /**
   * httpPost
   * 
   * @param url
   *          路径
   * @param jsonParam
   *          参数
   * @return
   */
  public static JSONObject httpPost(String url, JSONObject jsonParam) {
    return httpPost(url, jsonParam, false);
  }

  /**
   * post请求
   * 
   * @param url
   *          url地址
   * @param jsonParam
   *          参数
   * @param noNeedResponse
   *          不需要返回结果
   * @return
   */
  public static JSONObject httpPost(String url, JSONObject jsonParam, boolean noNeedResponse) {

    // post请求返回结果
    DefaultHttpClient httpClient = new DefaultHttpClient();
    JSONObject jsonResult = null;
    HttpPost method = new HttpPost(url);
    try {
      if (null != jsonParam) {
        // 解决中文乱码问题
        StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        method.setEntity(entity);
      }
      HttpResponse result = httpClient.execute(method);
      url = URLDecoder.decode(url, "UTF-8");
      /** 请求发送成功，并得到响应 **/
      if (result.getStatusLine().getStatusCode() == 200) {
        String str = "";
        try {
          /** 读取服务器返回过来的json字符串数据 **/
          str = EntityUtils.toString(result.getEntity());
          if (noNeedResponse) {
            return null;
          }
          /** 把json字符串转换成json对象 **/
          jsonResult = JSONObject.fromObject(str);
        } catch (Exception e) {
          logger.error("post请求提交失败:" + url, e);
        }
      }
    } catch (IOException e) {
      logger.error("post请求提交失败:" + url, e);
    }
    return jsonResult;
  }
  /**
   * post请求
   * 
   * @param url
   *          url地址
   * @param jsonParam
   *          参数
   * @param noNeedResponse
   *          不需要返回结果
   * @return
   */
  public static JSONObject httpPostForm(String url, List<BasicNameValuePair> pairList, boolean noNeedResponse) {
    JSONObject jsonResult = null;
    // post请求返回结果
    HttpPost httpPost = new HttpPost(url);
    try {
      CloseableHttpClient client = HttpClients.createDefault();
      httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));   
      
      HttpResponse result = client.execute(httpPost);
      url = URLDecoder.decode(url, "UTF-8");
      /** 请求发送成功，并得到响应 **/
      if (result.getStatusLine().getStatusCode() == 200) {
        String str = "";
        try {
          /** 读取服务器返回过来的json字符串数据 **/
          str = EntityUtils.toString(result.getEntity());
          if (noNeedResponse) {
            return null;
          }
          /** 把json字符串转换成json对象 **/
          jsonResult = JSONObject.fromObject(str);
        } catch (Exception e) {
          logger.error("post请求提交失败:" + url, e);
        }
      }
    } catch (IOException e) {
      logger.error("post请求提交失败:" + url, e);
    }
    return jsonResult;
  }
}